﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TC.SSO.Client.Common
{
    internal class Tools
    {
        /// <summary>
        /// unix时间转换为datetime
        /// </summary>
        /// <param name="timeStamp"></param>
        /// <returns></returns>
        public static DateTime UnixTimeToTime(string timeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime);
            return dtStart.Add(toNow);
        }

        /// <summary>
        /// datetime转换为unixtime
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static int ConvertDateTimeInt(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }

        public static string JsonSerializer(object obj)
        {
            Type type = obj.GetType();
            var jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            return jsonSerializer.Serialize(obj);
        }

        public static T JsonDeserializer<T>(string jsonString)
        {
            var jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            return jsonSerializer.Deserialize<T>(jsonString);
        }

        public static object JsonDeserializerObject(string jsonString)
        {
            var json = new System.Web.Script.Serialization.JavaScriptSerializer();
            return json.DeserializeObject(jsonString);
        }
    }


    internal sealed class Security
    {
        public static string EncryptString(string sourceString, string privateKey)
        {
            return EncryptString(sourceString, privateKey, System.Text.Encoding.UTF8);
        }
        public static string EncryptString(string sourceString, string privateKey, System.Text.Encoding encoding)
        {
            if (string.IsNullOrEmpty(sourceString))
            {
                throw new ArgumentNullException("sourceString");
            }
            if (encoding == null)
            {
                throw new ArgumentNullException("encoding");
            }
            System.Security.Cryptography.DESCryptoServiceProvider des = new System.Security.Cryptography.DESCryptoServiceProvider();
            byte[] buffer = encoding.GetBytes(sourceString);
            byte[] desKeyBuffer = System.Text.ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(privateKey, "md5").Substring(0, 8));

            des.Key = desKeyBuffer;
            des.IV = desKeyBuffer;
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, des.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
                cs.Write(buffer, 0, buffer.Length);
                cs.FlushFinalBlock();
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                foreach (byte b in ms.ToArray())
                {
                    sb.Append(b.ToString("X2"));
                }
                return sb.ToString();
            }
        }
        public static string DecryptString(string sourceString, string privateKey)
        {
            return DecryptString(sourceString, privateKey, System.Text.Encoding.UTF8);
        }
        public static string DecryptString(string sourceString, string privateKey, System.Text.Encoding encoding)
        {
            if (string.IsNullOrEmpty(sourceString))
            {
                throw new ArgumentNullException("sourceString");
            }
            if (encoding == null)
            {
                throw new ArgumentNullException("encoding");
            }
            System.Security.Cryptography.DESCryptoServiceProvider des = new System.Security.Cryptography.DESCryptoServiceProvider();
            int len = sourceString.Length / 2;
            byte[] buffer = new byte[len];
            int value;
            for (int i = 0; i < len; i++)
            {
                value = Convert.ToInt32(sourceString.Substring(i * 2, 2), 16);
                buffer[i] = (byte)value;
            }
            byte[] desKeyBuffer = System.Text.ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(privateKey, "md5").Substring(0, 8));

            des.Key = desKeyBuffer;
            des.IV = desKeyBuffer;
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, des.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
                cs.Write(buffer, 0, buffer.Length);
                cs.FlushFinalBlock();
                return encoding.GetString(ms.ToArray());
            }
        }
    }
}
